package servlets;

import bean.Goods;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import utils.GetRequestJsonUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PayServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        List<Goods> goodses = (List<Goods>) session.getAttribute("cart");
        double total = 0;
        int len = 0;
        if (goodses == null) {
            response.getWriter().write(session.getAttribute("name") + "<a href='/api/cart'>您还没有选购商品，请进入购物车选购商品<a/><br/>");
        } else {
            len = goodses.size();
            for (int i = 0; i < len; i++) {
                Goods goods = goodses.get(i);
                total = total + goods.getPrice() * goods.getCount();
            }
            response.getWriter().write(session.getAttribute("name") + ",请支付！金额为：" + total);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        使用工具类方法取出请求消息中的json数据
        request.setCharacterEncoding("utf-8");
//        如果请求消息中json字符串你能肯定是对象（开头{，结尾}），才能使用下面方法来转换
        JSONObject jsonObject = GetRequestJsonUtils.getRequestJsonObject(request);
//        将json数据中某一个键的内容取出
        String goodstext = jsonObject.getString("goodses");
        String selectCount = jsonObject.getString("selectCount");
        double total = jsonObject.getDoubleValue("total");
        String xjText = jsonObject.getString("xj");
        JSONArray goodsArray = JSONArray.parseArray(goodstext);
        JSONArray selectCountArray = JSONArray.parseArray(selectCount);
        JSONArray xjArray = JSONArray.parseArray(xjText);
        double s = 0;
        int n = 0;
        for (int i = 0; i < selectCountArray.size(); i++) {
            if (!selectCountArray.get(i).toString().equals("0")) {
                JSONObject goodsObject = JSONObject.parseObject(goodsArray.get(i).toString());
                s = s + goodsObject.getDoubleValue("price");
                n++;
                System.out.println("商品名：" + goodsObject.getString("name") + ",单价：" + goodsObject.getString("price").toString() + "商品数量：" + selectCountArray.get(i).toString());
            }
        }
        System.out.println("选购的商品平均价格是：" + s / n);


    }
}
